<?php
// 券模型
class CouponModel extends Model {
	/**生成券
	 *`id` bigint(20) unsigned NOT NULL COMMENT '主键，自增',
	  `order_id` bigint(20) unsigned NOT NULL COMMENT 'ID',
	  `passcode` varchar(80) NOT NULL COMMENT '券的唯一码（构成方式考虑下，多少位，密码多少位，商品编码多少位）',
	  `receiver_mobile` int(15) NOT NULL COMMENT '接收者电话号码',
	  `start_date` int(10) unsigned NOT NULL COMMENT '券开始使用日期',
	  `expired_date` int(10) unsigned NOT NULL COMMENT '券使用截止日',
	  `quantity` int(3) unsigned NOT NULL COMMENT '商品数量',
	  `message` varchar(40) NOT NULL COMMENT '祝福语',
	  `namecard` varchar(128) NOT NULL COMMENT '发送时用到的图片',
	  `target_date` int(10) NOT NULL COMMENT '预定发送日期',
	  `channel` varchar(15) NOT NULL COMMENT '发送方式sms,txt,email组成字符串以,分隔',
	  `is_send` enum('Y','N') NOT NULL DEFAULT 'Y' COMMENT '是否已发送',
	  `send_times` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '发送次数',
	  `checker_id` bigint(20) unsigned NOT NULL COMMENT '此券确认者，由此来明确是哪个分店',
	  `check_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '确认时间，添加了checker_id和check_time则为已使用',
	  `is_canceled` enum('Y','N') NOT NULL DEFAULT 'N' COMMENT '是否取消。管理员设置是否取消',
	  `cancel_reason` varchar(200) NOT NULL DEFAULT '' COMMENT '取消原因',
	  `cancel_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间，记录取消时间',
	  `ctime` int(10) unsigned NOT NULL COMMENT '创建时间',
	 *
	 * @param unknown_type $order_id	订单ID
	 * @param unknown_type $receivers	收礼人数组
	 * 									格式：["receivers"] => array(2) {
															    ["data"] => array(1) {
																      [0] => array(4) {
																        [0] => string(11) "13822222222"
																        [1] => string(1) "1"
																        [2] => string(10) "2011-04-16"
																        [3] => string(1) "0"
																      }
															    }
															    ["total_no"] => int(1)
														 }
	 
	 */
	public function addCoupon($order_id,$gid,$receivers,$send_format,$namecard='',$txtdata=''){
		Log::record('新增礼券：预计新增'.count($receivers).'个',Log::K_ORDER,Log::FILE);	
		if(empty($order_id)||empty($receivers)||empty($send_format))return 0;
	  	$coupon['order_id']=$order_id;// bigint(20) unsigned NOT NULL COMMENT 'ID',
	  	$coupon['message']=$txtdata;// ` varchar(40) NOT NULL COMMENT '祝福语',
	  	$coupon['namecard']=empty($namecard)?'':$namecard;// ` varchar(128) NOT NULL COMMENT '发送时用到的图片',
	  	$coupon['channel']=$send_format;// ` varchar(15) NOT NULL COMMENT '发送方式sms,txt,email组成字符串以,分隔',
	  	$coupon['is_send']='N';// ` enum('Y','N') NOT NULL DEFAULT 'Y' COMMENT '是否已发送',
	  	$coupon['send_times']=0;// ` int(1) unsigned NOT NULL DEFAULT '1' COMMENT '发送次数',
	  	$coupon['checker_id']=null;// ` bigint(20) unsigned NOT NULL COMMENT '此券确认者，由此来明确是哪个分店',
	  	$coupon['check_time']=null;// ` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '确认时间，添加了checker_id和check_time则为已使用',
	  	$coupon['is_canceled']='N';// ` enum('Y','N') NOT NULL DEFAULT 'N' COMMENT '是否取消。管理员设置是否取消',
	  	$coupon['cancel_reason']=null;// ` varchar(200) NOT NULL DEFAULT '' COMMENT '取消原因',
	  	$coupon['cancel_time']=null;// ` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '修改时间，记录取消时间',
	  	$coupon['ctime']=time();// ` int(10) unsigned NOT NULL COMMENT '创建时间',
		$coupon['goods_id']=$gid;
	  	$no = 0;
	  	$coupondao = $this;
	  	foreach($receivers as $vo){
	  		unset($coupon1);
	  		foreach($coupon as $key => $vo1 ){
	  			$coupon1[$key ]=$vo1;
	  		}
	  		unset($coupon1['id']);//=null;
	  		$coupon1['passcode']=$this->_generatePasscode($order_id);// ` varchar(80) NOT NULL COMMENT '券的唯一码（构成方式考虑下，多少位，密码多少位，商品编码多少位）',
		  	$coupon1['receiver_mobile']=$vo[0];// ` int(15) NOT NULL COMMENT '接收者电话号码',
		  	$coupon1['quantity']=$vo[1];// ` int(3) unsigned NOT NULL COMMENT '商品数量',
		  	$coupon1['target_date']=paramDate( $vo[2] );// ` int(10) NOT NULL COMMENT '预定发送日期',
		  	$coupon1['target_hour']=$vo[3];// ` int(10) NOT NULL COMMENT '预定发送时间',
		  	//$coupon1['start_date']=time();//  int(10) unsigned NOT NULL COMMENT '券开始使用日期',
		  	//$coupon1['expired_date']=time();// ` int(10) unsigned NOT NULL COMMENT '券使用截止日',
		  	Log::record('新增礼券：新增数据-> data=['.parseAry2Str($coupon1).']',Log::K_ORDER,Log::FILE);	
		  	$id=$coupondao->add($coupon1);
		  	Log::record('新增礼券：新增语句-> sql=['.$coupondao->getLastSql().']',Log::K_ORDER,Log::FILE);	
		  	Log::record('新增礼券：新增结果-> id=['.$id.']',Log::K_ORDER,Log::FILE);	
		  	if(!empty($id))$no = $no+1;
	  	}
	  	Log::save();
		return $no;
	}
	
	public function update2Active($order_id,$start_date=null,$expired_date=null){
		$map['is_active']='Y';
		if(!empty($start_date))$map['start_date']=$start_date;
		if(!empty($expired_date))$map['expired_date']=$expired_date;
		$no = $this->where('order_id='.$order_id." and is_active='N' ")->save($map);
		return $no;
	}
	
	
	/**
	 * 取消礼券。（不管发送与否）
	 * @param String $order_id
	 * @param String $cancel_reason
	 */
	public function chancelCoupon($order_id,$cancel_reason){
		$map['is_canceled']='Y';
		$map['cancel_reason']=$cancel_reason;
		$no = $this->where('order_id='.$order_id)->save($map);
		return $no;
	}
	
	/**生成passcode**/
	private function _generatePasscode($order_id){
		return time().rand(1000, 9999);
	}
	
	
	/*
	 *	查询礼券
	 */
	public function search4Sys($map ,$order='ctime desc', $limit = 20) {
		$where = $this->_getSelectCondition($map);
		//$order='ctime desc';
		$pagedata = $this->kPageQuery($where,$order,$limit);
		//dump(M('')->getLastSql());
		//dump($pagedata);
		return $pagedata;
	}
	
	
	public function search4SH($map ,$order='ctime desc', $limit = 20){
		$map['is_used']='Y';
		$map['is_send']=='Y';
		return $this->search4Sys($map ,$order, $limit);
	}
	
	
	/**
	 * 查询所有或指定订单未发送过的数据（某发送时间点内的数据）。该方法一般用于系统自动发送数据时。
	 * @param unknown_type $limittime	发送时间电（单位秒），发送时间小于等于该时间的将查询出。
	 * @param unknown_type $order_id	订单ID，可为空。
	 * @param unknown_type $limit
	 */
	public function selectCoupon4Send($limittime, $order_id=null, $limit = 20){
		$dateAry = paramMillisecond2Ary($limittime);
		if(!empty($order_id)){
			$where = " `order_id`={$order_id} and ";
		}
		$target_date = paramDate( $dateAry['year'].'-'.$dateAry['month'].'-'.$dateAry['day'] );
		$target_hour = intval($dateAry['hour']);

		$where = $where." (`target_date`<{$target_date} or ( `target_date`={$target_date} and `target_hour`<={$target_hour} ) ) ";
		$where = $where." and `is_send`='N' and `is_canceled`='N' and `is_active`='Y' ";
		//$coupondao = model('Coupon');
		if(!empty($limit))$tobesendList = $this->where($where)->limit($limit)->findAll();
		else $tobesendList = $this->where($where)->findAll();
		Log::record("CouponModel.selectCoupon4Send()sql=".$this->getLastSql(),Log::K_ORDER,Log::FILE);
		Log::save(); 
		return $tobesendList;
	}
	
	
	/**
	 * 用户出发查询指定礼券数据，重新发送。
	 */
	public function selectCoupon4ReSend($where){
		$where['is_canceled']='N';
		$where['is_active']='Y';
		unset($where['is_send']);
		//$coupondao = model('Coupon');
		$tobesendList = $this->where($where)->findAll();
		Log::record("CouponModel.selectCoupon4ReSend()sql=".$this->getLastSql(),Log::K_ORDER,Log::FILE);
		Log::save(); 
		return $tobesendList;
	}
	
	/**
	 * 计算相应礼券对应商品总数
	 * @param unknown_type $map
	 */
	public function countQuantity($map){
		//dump($map);
		$where = $this->_getSelectCondition($map);
		//dump($where);
		$sum = $this->where($where)->field(' sum(`quantity`) as `sum` ')->find();
		//dump($this->getLastSql());
		return $sum['sum'];
	}
	
	
	/**
	 * 统一使用的查询条件转换方法
	 * @param unknown_type $map
	 */
	private function _getSelectCondition($map){
		if(!empty($map['gid'])){
			if(is_array($map['gid'])){
				$where ['goods_id'] = array('in',$map['gid']);
			}else{
				$where ['goods_id'] = $map['gid'];
			}
		}
		if(!empty($map['orderId'])){
			$where['order_id']=$map['orderId'];
		}
		if(!empty($map['passcode'])){
			$where['passcode']=$map['passcode'];
		}
		if(!empty($map['receiver_mobile'])){
			$where['receiver_mobile']=$map['receiver_mobile'];
		}
		
		if($map['is_send']=='Y'||$map['is_send']=='N'||$map['is_send']=='E'){
			$where['is_send']=$map['is_send'];
		}
		
		if($map['is_active']=='Y'||$map['is_active']=='N'){
			$where['is_active']=$map['is_active'];
		}
		
		if($map['is_canceled']=='Y'||$map['is_canceled']=='N'){
			$where['is_canceled']=$map['is_canceled'];
		}
		
		if($map['is_expired']=='N'){
			$where['expired_date']=array('gt',time());
		}
		if($map['is_expired']=='Y'){
			//$where['expired_date']=array('gt',time());
			//$where['expired_date']=array('NEQ',0);
			$where['expired_date']=array(array('lt',time()),array('NEQ',0),'and'); 
		}
		if(!empty($map['pid'])){
			if(is_array($map['pid'])){
				$where ['checker_id'] = array('in',$map['pid']);
			}else{
				$where ['checker_id'] = $map['pid'];
			}
		}
		if($map['is_used']=='Y'){
			if(empty($where ['checker_id']))$where['checker_id']=array('gt',0);
			$where['check_time']=array('gt',0);
		}
		if($map['is_used']=='N'){
			//$where['check_time']=array('elt',0);
			$where['checker_id']=array('elt',0);
			$where['check_time'] = array(array('EXP',' is null '),array('elt',0),'or'); //id >= 10 or id <=3
			//$where['check_time'] = array('EXP','11');
		}
		
		//如果查询条件为空，则加此。是查询为空。
		if(empty($where))$where=" 1=2 ";
		
		return $where;
	}
}
?>